package code.lewdy.lottery;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import lottery.BetRecord;
import lottery.Lottery;
import lottery.PayReward;
import code.lewdy.db.Database;
import code.lewdy.db.HibernateTemple;
import code.lewdy.db.JdbcTemple;
import code.lewdy.db.JdbcUtil;
import code.lewdy.time.TimeHelper;

public class LotteryService {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// System.out.println(getLotteryList().size());
		LotteryService ls = new LotteryService();
		System.out.println(ls.hasRepeat("123|345|423|129"));
		//System.out.println(ls.getNewNumberId(12));
		//System.out.println(ls.getNewRewardNumber(8).getNumber());
		//System.out.println(ls.getOpenTimeLeft(8));
		//ls.getOpenRewardsTask();
	}
	
	

	private static List<Lottery> lotteryList = new ArrayList<Lottery>();
	private static boolean init = false;
	private LotteryHelper helper = new LotteryHelper();
	PayReward pay = new PayReward(); // 派奖类
	private JdbcUtil jdbc = new JdbcUtil(Database.TYPE_MYSQL);
	
	/**是否有重复号码
	 * @param number
	 * @return
	 */
	public static boolean hasRepeat(String number){
		String arr[] = number.split("\\|");
		List<String> list = new ArrayList<String>();
		for(String s : arr){
			if(list.contains(s)){
				return true;
			}
			list.add(s);
		}
		return false;
	}
	
	/**获取注数
	 * @param number
	 * @param betName
	 * @return
	 */
	public static int getCount(String number, String betName){
		if(betName == null ||  betName.indexOf("单式")<0){
			return -1;
		}
		int count = number.split("\\|").length;
		return count;
	}
	/**获取开奖剩余时间
	 * @param lotteryId
	 * @return
	 */
	public int getOpenTimeLeft(int lotteryId){
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		int s = hour * 3600 + minute * 60 + second;
		int left = 0;
		if(lotteryId == 11 && hour==23){  //天津时时彩
			return 10*3600 + 600 - (minute*60 + second);
		}else if(lotteryId == 9 && hour==23 && minute>=14){ //江西时时彩
			return 9*3600 + 2760 + 600 - (minute*60 + second);
		}else if(lotteryId == 14 || lotteryId==15){ //3D或P3
			if(s > TimeHelper.getSecondsByTime("20:30:00")){//20:30以后
				left = (24*3600+TimeHelper.getSecondsByTime("20:30:00")) - s;
				return left;
			}else{
				left = TimeHelper.getSecondsByTime("20:30:00") - s;
				if(left > 30*60){
					left = left - 30*60;
				}
				return left;
			}
		}
		String monthStr = "";
		if((month+"").length() == 1){
			monthStr = "0" + month;
		}else{
			monthStr = "" + month;
		}
		
		String prefix = year + "" + monthStr + "" + day;
		int  openTime = (Integer)HibernateTemple.getUniqueResult("select openTime from LotteryOpenTime where "
						+ " lotteryId=" + lotteryId + " and openTime > " + s
						+ " and beginTime < " + s);
		/* jdbc
		int  openTime = jdbc
				.getInt("select openTime from LotteryOpenTime where "
						+ " lotteryId=" + lotteryId + " and openTime > " + s
						+ " and beginTime < " + s);
		*/
		return openTime - s;
	}
	
	/**
	 * 获取数据库中最新的开奖号码
	 * 
	 * @param lotteryId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public OpenRewardNumber getNewRewardNumber(int lotteryId) {
		/* jdbc
		String newNumberId = jdbc
				.getString("SELECT max(periodNo) from OpenRewardNumber where lotteryId="
						+ lotteryId);
		String sql = "SELECT * from OpenRewardNumber where periodNo = '"
				+ newNumberId + "'";
		OpenRewardNumber num = (OpenRewardNumber) jdbc.getEntityBySQL(
				OpenRewardNumber.class.getName(), sql);
		*/
		String newNumberId = (String) HibernateTemple.getUniqueResult("select max(periodNo) as mp from OpenRewardNumber " +
				" where lotteryId="+lotteryId);
		List<OpenRewardNumber>nums = (List<OpenRewardNumber>) HibernateTemple.list("from OpenRewardNumber" +
				" where periodNo='"+newNumberId+"' and lotteryId="+lotteryId);
		if(nums.size() > 0){
			OpenRewardNumber num = nums.get(0);
			return num;
		}else{
			System.out.println("获取最新开奖号码出错！");
			return null;
		}
	}

	/**
	 * 获取当前时段期号
	 * 
	 * @param lotteryId
	 * @return
	 */
	public String getNewNumberId(int lotteryId) {
		if(lotteryId==14){ //3D
			return P33DUtil.get3DNumberId(new Date());
		}else if(lotteryId == 15){ //P3
			return P33DUtil.getP3NumberId(new Date());
		}
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		int s = hour * 3600 + minute * 60 + second;
		String numberId = "";
		String monthStr = "";
		String dayStr = (""+day).length()==1 ? ("0"+day) : (""+day);
		if((month+"").length() == 1){
			monthStr = "0" + month;
		}else{
			monthStr = "" + month;
		}
		//if(h)
		String prefix = year + "" + monthStr + "" + dayStr;
		List<LotteryOpenTime> ots = (List<LotteryOpenTime>) HibernateTemple.list("from LotteryOpenTime where "
						+ " lotteryId=" + lotteryId + " and openTime > " + s
						+ " and beginTime < " + s);
		if(ots.size() > 0){
			LotteryOpenTime ot = ots.get(0);
			String numberIdSuffix = ot.getNumberIdSuffix();
			if(Integer.parseInt(numberIdSuffix)==1 && hour>=22){
				//22点以后期号为1，实际是第二天的第一期，day++
				day ++;
				prefix = year + "" + monthStr + "" + day;
			}
			if(lotteryId == 12){ //新疆时时彩
				if(hour>=0 && hour<5){ //凌晨0点以后日期还是前一天的
					day --;
					if(day == 0){
						month--;
						if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
							day = 31;
						}else if(month==4 || month==6 || month==9 || month==11){
							day = 30;
						}else{
							day = 28;
						}
					}
					dayStr = day<10 ? "0"+day : ""+day;
					prefix = year + monthStr + dayStr;
				}
			}
			numberId = prefix + numberIdSuffix;
			System.out.println(numberId);
		}else{
			System.out.println("获取开奖期号错误=>lotteryId:"+lotteryId);
		}
		return numberId;
	}

	/**
	 * 任务调度方法，以在合适的时间采集开奖号码
	 */
	int remain = 0; // 开奖剩余时间

	public void getOpenRewardsTask() {
		if (!init)
			init();
		for (Lottery lottery : lotteryList) {
			//remain = LotteryTimeManager.getRemainderTime(lottery.getName());
			updateRewardNumber(lottery); // 更新开奖号码到数据库
			/*
			if ((remain < 60 || (remain>=240 && remain<=600))
					&& remain >= 0 ) {
				updateRewardNumber(lottery); // 更新开奖号码到数据库
			}
			*/
		}
	}

	/**
	 * 更新开奖号码到数据库
	 * 
	 * @param lottery
	 */
	private void updateRewardNumber(Lottery lottery) {
		// TODO Auto-generated method stub
		OpenRewardNumber num = null;
		num = helper.getLatestRewardNumber(null, lottery.getId(), lottery
				.getName());
		if (num == null) {
			//System.out.println("collect open number fail : " + lottery.getName());
			return;
		}
		String checkSql = "select count(*) from OpenRewardNumber where lotteryId="
				+ lottery.getId()
				+ " and periodNo='" + num.getPeriodNo()+ "'";
		long count = (Long)HibernateTemple.getUniqueResult(checkSql);
		if (count > 0) {
			System.out.println("OPEN NO UPDATED....");
			return;
		}
		if(count>0){
			System.out.println("!!REPEATE INSERT INTO OPEN NO......");
		}
		// 保存到数据库
		num.setLotteryId(lottery.getId());
		num.setLotteryName(lottery.getName());
		num.setBetStopTime(new Date());
		HibernateTemple.save(num);
		/*System.out.println("开奖号码更新:" + lottery.getName() + "--"
				+ num.getPeriodNo() + "--" + num.getNumber());*/
		// 更新投注记录中的开奖号码
		int updater = JdbcTemple
				.executeUpdate("update BetRecord set openRewardNumber='"
						+ num.getNumber() + "' where numberId='"
						+ num.getPeriodNo() + "' and lotteryId="
						+ num.getLotteryId());
		payReward(num); // 开奖派奖
		System.out.println("LID-"+num.getLotteryId()+ " PAY REWARD:BetRecord("
				+ updater + ")");
	}

	/**
	 * 按开奖号码自动派奖
	 * 
	 * @param num
	 *            开奖号码
	 */
	public void payReward(OpenRewardNumber num) {
		List<BetRecord> brs = (List<BetRecord>) jdbc.list("lottery.BetRecord",
				"where lotteryId=" + num.getLotteryId() + " and numberId='"
						+ num.getPeriodNo() + "'", 1, 10000);
		for (BetRecord br : brs) {
			if (br == null) {
				return;
			}
			int results = pay.doPay(br);
		}
	}

	public static List<Lottery> getLotteryList() {
		if (!init)
			init();
		return lotteryList;
	}

	private static void init() {
		lotteryList.add(new Lottery().instance(8,
				LotteryConstant.LOTTERY_CHONGQING_NAME));
		lotteryList.add(new Lottery().instance(9,
				LotteryConstant.LOTTERY_JIANGXI_NAME));
		lotteryList.add(new Lottery().instance(10,
				LotteryConstant.LOTTERY_HLJSSC_NAME));
		lotteryList.add(new Lottery().instance(11,
				LotteryConstant.LOTTERY_TIANJIN_NAME)); //天津时时彩
		lotteryList.add(new Lottery().instance(12,
				LotteryConstant.LOTTERY_XINJIANG_NAME)); //新疆时时彩
		lotteryList.add(new Lottery().instance(13,
				LotteryConstant.LOTTERY_SHANGHAISSL_NAME)); //上海时时乐
		lotteryList.add(new Lottery().instance(14,
				LotteryConstant.LOTTERY_3D_NAME)); 
		lotteryList.add(new Lottery().instance(15,
				LotteryConstant.LOTTERY_P3_NAME));
		lotteryList.add(new Lottery().instance(16,
				LotteryConstant.LOTTERY_11YDJ_NAME));
		lotteryList.add(new Lottery().instance(17,
				LotteryConstant.LOTTERY_11X5_NAME));
		lotteryList.add(new Lottery().instance(18,
				LotteryConstant.LOTTERY_GD11X5_NAME));
		lotteryList.add(new Lottery().instance(19,
				LotteryConstant.LOTTERY_GDKLSF_NAME)); //广东快乐十分
		lotteryList.add(new Lottery().instance(20,
				LotteryConstant.LOTTERY_TIANJINKLSF_NAME));
		lotteryList.add(new Lottery().instance(25,
				LotteryConstant.LOTTERY_BJKL8_NAME));
		init = true;
	}

}
